package com.wuuxiang.polestar.core.spring.surpass;

import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.w3c.dom.Element;

import java.util.List;

/**
 * 项目名称：polestar        <br>
 * 类描述：                         <br>
 * 创建人：夏鸿鹏                    <br>
 * 创建时间：2017-12-5 17:31        <br>
 * 修改备注：                        <br>
 */

public class PolestarPropertySourcesPlaceholderSurPassConfigurerConfigBean extends AbstractSingleBeanDefinitionParser {
    @Override
    protected Class<?> getBeanClass(Element element) {
        return PropertySourcesPlaceholderConfigurer.class;
    }

    @Override
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        builder.addPropertyValue("order", Integer.parseInt(element.getAttribute("order")));
        builder.addPropertyValue("ignoreUnresolvablePlaceholders", Boolean.valueOf(element.getAttribute("ignore-unresolvable-placeholders")));

        List<Object> list = parserContext.getDelegate().parseListElement(element, builder.getRawBeanDefinition());

        // Register property sources
        BeanDefinitionBuilder configGroupSourceFactoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(PolestarSurPassGroupSourceFactory.class);
        configGroupSourceFactoryBuilder.setFactoryMethod("create");
		String configProfileRef = element.getAttribute("config-profile-ref");
		configGroupSourceFactoryBuilder.addConstructorArgReference(configProfileRef);
        configGroupSourceFactoryBuilder.addConstructorArgValue(list);
        String generatedSourceFactoryName = parserContext.getReaderContext().generateBeanName(configGroupSourceFactoryBuilder.getRawBeanDefinition());
        parserContext.registerBeanComponent(new BeanComponentDefinition(configGroupSourceFactoryBuilder.getBeanDefinition(), generatedSourceFactoryName));

        builder.addPropertyValue("propertySources", new RuntimeBeanReference(generatedSourceFactoryName));
    }
}
